package com.hzzc.core.service;

import com.hzzc.BizException;
import com.hzzc.core.dao.SSOUserMapper;
import com.hzzc.core.model.SSOUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * 后台用户服务
 */
@Service
public class UserService {

    @Autowired
    private SSOUserMapper ssoUserMapper;

    @Autowired
    private PasswdEncoder passwdEncoder;

    /**
     * 根据Id倒叙排序
     *
     * @return
     */
    public List<SSOUser> userList() {
        Example example = new Example(SSOUser.class);
        example.orderBy("id").desc();
        return ssoUserMapper.selectByExample(example);
    }


    /**
     * 增加新用户
     *
     * @param name
     * @param head
     * @param account
     * @param pwd
     * @param black
     * @throws BizException
     */
    public void addUser(String name, String head, String account, String pwd, boolean black) throws BizException {
        SSOUser ssoUser = new SSOUser();
        ssoUser.setAccount(account);
        ssoUser.setHead(head);
        ssoUser.setName(name);
        ssoUser.setPwd(passwdEncoder.encode(pwd));
        ssoUser.setBlack(black);
        ssoUserMapper.insert(ssoUser);
    }

    /**
     * 更具Id获取用户
     *
     * @param userId
     * @return
     */
    public SSOUser selectById(long userId) {
        return ssoUserMapper.selectByPrimaryKey(new SSOUser().setId(userId));
    }

    public void delUser(Long userId) {
        ssoUserMapper.deleteByPrimaryKey(userId);
    }

    public void updateUser(Long id, String name, String head, String account, String pwd, boolean black) {
        SSOUser ssoUser = new SSOUser();
        ssoUser.setId(id);
        ssoUser.setAccount(account);
        ssoUser.setHead(head);
        ssoUser.setName(name);
        ssoUser.setBlack(black);
        ssoUser.setPwd(passwdEncoder.encode(pwd));
        ssoUserMapper.updateByPrimaryKey(ssoUser);
    }
}
